from django.core.files.storage import Storage
from fdfs_client.client import Fdfs_client
from django.conf import settings


class FastDFSStorage(Storage):
    """实现django对fdfs的文件存储"""

    def __init__(self, client_conf=None, server_ip=None):
        """初始化方法,设置参数"""
        if client_conf is None:
            # 当外界没有传入 client_conf
            client_conf = settings.CLIENT_CONF
        self.client_conf = client_conf

        if server_ip is None:
            server_ip = settings.SERVER_IP
        self.server_ip = server_ip

    def _open(self, name, mode='rb'):
        """打开文件时调用"""
        pass

    def _save(self, name, context):
        """name是要上传文件的名字,context 是file对象,提供read()  获取文件内容!"""

        # 创建fdfs对接的对象
        client = Fdfs_client(self.client_conf)

        # 获取要上传的文件内容!
        file_data = context.read()

        # 调用上传的方法,并接收返回值
        try:
            ret = client.upload_by_buffer(file_data)
        except Exception as e:
            print(e)
            raise

        if ret.get('Status') == 'Upload successed.':
            file_id = ret.get('Remote file_id')
            # 封装好的  返回id 自动保存到属性中!
            return file_id

        else:
            raise Exception('上传失败!')

    def exists(self,name):
        return False

    def url(self, name):
        """返回保存的文件的路径, name 表示保存文件的路径!"""

        return self.server_ip + name


"""
>>> from fdfs_client.client import *
>>> client = Fdfs_client('/etc/fdfs/client.conf')
>>> ret = client.upload_by_filename('test')
>>> ret
{'Group name':'group1','Status':'Upload successed.', 'Remote file_id':'group1/M00/00/00/
wKjzh0_xaR63RExnAAAaDqbNk5E1398.py','Uploaded size':'6.0KB','Local file name':'test'
, 'Storage IP':'192.168.243.133'}
"""
